package org.snusmumr.android.media;

import java.util.ArrayList;

import org.snusmumr.android.media.data.DatabaseProvider;
import org.snusmumr.android.media.data.DatabaseProvider.DatabaseMode;
import org.snusmumr.android.media.data.MediaColumns;
import org.snusmumr.android.media.data.UnlentItemsOperation;
import org.snusmumr.android.media.data.adapter.LentItemsListAdapter;
import org.snusmumr.android.media.data.adapter.LentItemsListAdapter.LentItemsGroupBy;

import android.app.ExpandableListActivity;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.Toast;

/**
 * @author Denis Kruglyakov
 */
public class LentItemsTab extends ExpandableListActivity {
	private static final String TAG = LentItemsTab.class.getSimpleName();
	
	private DatabaseProvider dbProvider;
	private LentItemsListAdapter adapter;
	
	private LentItemsGroupBy groupBy = LentItemsGroupBy.Friend;
	
	public interface OnCheckedListener {
		public void onChecked(int selectionCount);
	}
	
	private OnCheckedListener itemCheckedListener = new OnCheckedListener() {
		@Override
		public void onChecked(int selectionCount) {
			if(selectionCount > 0) 
				showButtonsPanel();
			else
				hideButtonsPanel();
		}
	};
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		dbProvider = DatabaseProvider.getInstance(this);

        setContentView(R.layout.lent_items_list);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		releaseResources();
	}

	private void releaseResources() {
		if(adapter != null)
			adapter.closeCursor();
		dbProvider.close();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		loadData();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.lent_tab_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		switch (groupBy) {
		case Friend:
			menu.findItem(R.id.mn_group_by_friend).setVisible(false);
			menu.findItem(R.id.mn_group_by_author).setVisible(true);
			break;
		case Author:
			menu.findItem(R.id.mn_group_by_friend).setVisible(true);
			menu.findItem(R.id.mn_group_by_author).setVisible(false);
			break;
		default:
			break;
		}
		
		return super.onPrepareOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mn_group_by_friend:
			if(groupBy != LentItemsGroupBy.Friend) {
				groupBy = LentItemsGroupBy.Friend;
				releaseResources();
				loadData();
			}
			return true;
		case R.id.mn_group_by_author:
			if(groupBy != LentItemsGroupBy.Author) {
				groupBy = LentItemsGroupBy.Author;
				releaseResources();
				loadData();
			}
			return true;
		case R.id.mn_settings:
			Toast.makeText(this, "settings selected", Toast.LENGTH_SHORT).show();
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void loadData() {
		Log.i(TAG, "Start loading data");
		final Resources res = getResources();
		int queryId = R.string.sql_fetch_friends_lent_items;
		String groupColumnDBName = MediaColumns.LENT_TO_NAME;
		switch (groupBy) {
		case Friend:
			queryId = R.string.sql_fetch_friends_lent_items;
			groupColumnDBName = MediaColumns.LENT_TO_NAME;
			break;

		case Author:
			queryId = R.string.sql_fetch_authors_lent_items;
			groupColumnDBName = MediaColumns.AUTHOR_NAME;
			break;
			
		default:
			break;
		}
		SQLiteDatabase database = dbProvider.getDatabase(DatabaseMode.Read);
		Cursor cursor = database.rawQuery(res.getString(queryId), null);
		
		if(cursor != null) {
			adapter = new LentItemsListAdapter(this, 
						cursor, 
						android.R.layout.simple_expandable_list_item_1, 
						new String[]{groupColumnDBName}, 
						new int[] { android.R.id.text1}, 
						R.layout.lent_item_content,
						new String[]{
							MediaColumns.AUTHOR_NAME,
							MediaColumns.ITEM_NAME,
							MediaColumns.LEND_DATE,
							MediaColumns.LENT_TO_NAME
						}, new int[]{
							R.id.tv_lent_item_author,
							R.id.tv_lent_item_name,
							R.id.tv_lent_date,
							R.id.tv_lent_by_friend
						}, itemCheckedListener, groupBy);
			setListAdapter(adapter);
		}
		
	}
	
	private void hideButtonsPanel() {
		View buttonsPanel = findViewById(R.id.lend_buttons_panel);
		if(buttonsPanel != null)
			buttonsPanel.setVisibility(View.INVISIBLE);
	}

	private void showButtonsPanel() {
		View buttonsPanel = findViewById(R.id.lend_buttons_panel);
		if(buttonsPanel == null) {
			buttonsPanel = ((ViewStub) findViewById(R.id.stub_lend_buttons_panel)).inflate();
			Button lendBtn = (Button) buttonsPanel.findViewById(R.id.btn_item_lend);
			lendBtn.setVisibility(View.INVISIBLE);
			Button unlendBtn = (Button) buttonsPanel.findViewById(R.id.btn_item_unlend);
			unlendBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					hideButtonsPanel();
					ArrayList<Long> listIds = adapter.getSelectedItemIds();
					final long[] itemsId = new long[listIds.size()];
					for(int i=0; i<listIds.size(); i++)
						itemsId[i] = listIds.get(i).longValue();
					Boolean unlent = new UnlentItemsOperation(LentItemsTab.this, itemsId).execute();
					if(Boolean.TRUE.equals(unlent))
						loadData();
				}
			});
		} else {
			buttonsPanel.setVisibility(View.VISIBLE);
		}
	}
}
